import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Dropdown } from 'primeng/dropdown';
import { RDataConfig } from '../r-models/r-table.model';

@Injectable({
  providedIn: 'root'
})

/**
 * 公司：xxx有限公司
 * 版权：xxx2020
 * 描述：下拉列表的方法，控制下拉列表点击动态加载
 * 作者：oyjl
 * 时间：2020-03-11 09:56:38
 */
export class RDropdownService {

  constructor(private http: HttpClient) { }

  /**
   * 描述：发送下拉请求，并设置下拉列表值，修改下拉icon，特别说明：如果需要动态拼接，需要传递args2(表示新拼接的字段)，join(数组结构，符号、字段用字符串表示，其中字段用f-区分)
   * 作者：oyjl
   * 时间：2020-03-11 09:59:54
   */
  public getDropdown(
    dropdown: Dropdown,
    url,
    args2,
    join: Array<string> = [],
    args3: string = 'data',
    args4: object = { pageInfo: { pageIndex: 1, pageSize: 10000000 } },
    args5: RDataConfig = { key: 'data', status: 'status', value: 200 }) {
    const classList = dropdown.containerViewChild.nativeElement.childNodes[6].childNodes[0].classList;
    classList.remove('pi', 'pi-chevron-down');
    classList.add('fa', 'fa-spinner');
    if (!classList.contains('pi-chevron-up')) {
      this.http.post(url, args4).subscribe((res: any) => {
        if (this.afterStatusSwitch(args5, res)) {
          const fields = args3.split('.');
          let dropdownOption = res;
          for (const item of fields) {
            if (item && item !== '') {
              dropdownOption = dropdownOption[item];
            }
          }
          if (typeof args2 === 'string' && args2 && join.length > 0) {
            (dropdownOption || []).forEach(item => {
              let tempStr = '';
              join.forEach(element => {
                if (element.includes('f-') && element.split('f-')[1]) {
                  tempStr += item[element.split('f-')[1]];
                } else {
                  tempStr += element;
                }
              });
              item[args2] = tempStr;
            });
          }
          dropdown.options = dropdownOption;
          classList.remove('fa', 'fa-spinner');
          classList.add('pi', 'pi-chevron-up');
        }
      }, (err => {
        dropdown.options = [];
      })
      );
    }
    if (classList.contains('pi-chevron-up')) {
      classList.remove('pi', 'pi-chevron-up');
      classList.add('pi', 'pi-chevron-down');
    } else if (classList.contains('pi-chevron-down')) {
      classList.remove('pi', 'pi-chevron-down');
      classList.add('pi', 'pi-chevron-up');
    } else { }
  }

  /**
   * 描述：后端状态处理
   * 作者：oyjl
   * 时间：2020-04-22 10:18:55
   */
  public afterStatusSwitch(dataConfig: RDataConfig, res): boolean {
    if (res[dataConfig.status] === dataConfig.value) {
      return true;
    }
    return false;
  }
}
